/*
 * BanBu_Voice_ViewController
 * @description 本文件提供个人空间设置语音签名的viewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供个人空间设置语音签名的viewController
 */

#import "BanBu_Voice_ViewController.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "Profile.h"
#import "BanBu_PersonDataViewController.h"
#import "RecordAudio.h"
@interface BanBu_Voice_ViewController ()
{
    UIImageView *animationBackgroundView;
    UIActivityIndicatorView *loadingView;
    UIButton    *setVoiceBtn;
    BOOL playing;
}
@end

@implementation BanBu_Voice_ViewController


- (void)dealloc {
    if(playing)
    {
        _player.delegate = nil;
        [_player stop];
    }
    
    if(loadingView)
    {
        [loadingView release],loadingView = nil;
    }
    if(animationBackgroundView){[animationBackgroundView release],animationBackgroundView = nil;}
    [_HeaderView release];
    [_voiceView release];
    [_bg release];
    [_soundList release],_soundList = nil;
    if (_recordView)
    {
        _recordView = nil;
    }
    [super dealloc];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableview.tableHeaderView = self.HeaderView;
    [self getVoiceDefault];
    [self dataInit];
    voiceLa.text = NSLocalizedString(@"voice_signature", nil);
    recommendLa.text = NSLocalizedString(@"voice_recommend", nil);
    [recordBu setTitle:NSLocalizedString(@"recore_voice", 录音) forState:UIControlStateNormal];
    _longPressLa.textColor = UIColorWithRGB(115, 115, 116, 1.0);
    _longPressLa.text = NSLocalizedString(@"album_voice_notice", nil);
    //录音时长按
    UILongPressGestureRecognizer *aLongPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(record:)];
    [recordBu addGestureRecognizer:aLongPress];
    [aLongPress release];
}

/**
 *	@brief	数据初始化
 */
-(void)dataInit
{
    _soundList = [[NSMutableArray alloc] initWithCapacity:0];
}
/**
 *	@brief	获取语音列表
 */
- (void)getVoiceDefault
{
    [AppComManager getBanBuData:BanBu_Get_Space_Picture_Sound_List par:[NSDictionary dictionaryWithObjectsAndKeys:@"sound",@"getby", nil] delegate:self];
}

/**
 *	@brief	设置语音
 *
 *	@param 	_url 设置的语音url
 */
- (void)setVoiceIntroduce:(NSString *)_url
{
    [AppComManager getBanBuData:BanBu_Set_Spaceset_Byuser par:[NSDictionary dictionaryWithObjectsAndKeys:_url,@"valueof",KEY_VOICE,@"keyof",nil] delegate:self];
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.soundList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell== nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    cell.backgroundColor = [UIColor clearColor];
    
   cell.textLabel.text = [NSString stringWithFormat:@"%d",indexPath.row+1];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    //UIActivityIndicatorView Add
    if(loadingView)
    {
        [loadingView removeFromSuperview];
        [loadingView release],loadingView = nil;
    }
    loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    loadingView.center = CGPointMake(200, 20);
    loadingView.hidesWhenStopped = YES;
    loadingView.backgroundColor = [UIColor redColor];
    [cell.contentView addSubview:loadingView];
    
    //播放 BanBu_PersonMusicPlay
    _player = [BanBu_PersonMusicPlay sharePlayer];
    [_player stop];
    _player.delegate = self;
    _player.loadUrl = [[self.soundList objectAtIndex:indexPath.row] valueForKey:@"urlof"];
    [_player startPlay];
    
 
    //播放中 UIImageView
    if(animationBackgroundView){
        [animationBackgroundView release];
        [animationBackgroundView removeFromSuperview];
    }
    animationBackgroundView = [[UIImageView alloc]initWithFrame:CGRectMake(120, 10, 60, 25)];
    [animationBackgroundView setImage:[UIImage imageNamed:@"广播详情-复选框-播放_空.png"]];
    [cell.contentView addSubview:animationBackgroundView];
    if(!animationBackgroundView) {return;}
    
    NSArray *animationImages = [NSArray arrayWithObjects:@"feed_comment_player_pause_anim1.png",@"feed_comment_player_pause_anim2.png",@"feed_comment_player_pause_anim3.png", nil];
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:3];
    for(NSString *path in animationImages)
    {
        [images addObject:[UIImage imageNamed:path]];
    }
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    imageView.frame = CGRectMake(13, 6.5, 10, 12);
    imageView.userInteractionEnabled = YES;
    imageView.animationImages = images;
    imageView.animationDuration = 1.0;
    imageView.animationImages = images;
    imageView.animationDuration = 1.0;
    
    imageView.backgroundColor = [UIColor clearColor];
    [animationBackgroundView addSubview:imageView];
    [imageView startAnimating];
    [imageView release];
    animationBackgroundView.hidden = NO;
    
    if(setVoiceBtn)
    {
        [setVoiceBtn removeFromSuperview];
        setVoiceBtn = nil;
    }
    
    setVoiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    setVoiceBtn.frame = CGRectMake(180, 0, 140, 45);
    setVoiceBtn.titleLabel.font = [UIFont systemFontOfSize:13.0];
    setVoiceBtn.tag = indexPath.row +1;
    [setVoiceBtn setTitle:NSLocalizedString(@"confirmSet", nil) forState:UIControlStateNormal];
    [setVoiceBtn addTarget:self action:@selector(setAsVoice:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:setVoiceBtn];
}


/**
 *	@brief	setVoiceBtn 的action 设置语音
 *
 *	@param 	sender 	setVoiceBtn
 */
-(void)setAsVoice:(UIButton *)sender
{
    [self setVoiceIntroduce:[[self.soundList objectAtIndex:sender.tag - 1] valueForKey:@"urlof"]];
}

-(void)musicDidStartPlay:(BanBu_PersonMusicPlay *)_player
{
    if(loadingView)
    {
        [loadingView removeFromSuperview];
        [loadingView release],loadingView = nil;
    }
    playing = YES;
    animationBackgroundView.hidden = NO;

//    [self animation];
}
-(void)musicDidEndPlay:(BanBu_PersonMusicPlay *)_player
{
    animationBackgroundView.hidden = YES;
}



- (void)record:(UILongPressGestureRecognizer *)longPress
{
    [self.view endEditing:YES];
    UIButton *button = (UIButton *)longPress.view;
    if(button.selected)
    {
        CGPoint point = [longPress locationInView:_recordView];
        if(longPress.state == UIGestureRecognizerStateEnded)
        {
            button.selected = NO;
            [_recordView touchesEndInView:point];
            _recordView = nil;
        }
        else
            [_recordView touchesMovedInView:point];
        
        return;
    }
    if (longPress.state == UIGestureRecognizerStateBegan)
    {
        button.selected = YES;
        RecordView *recordView = [[RecordView alloc] initWithFrame:CGRectMake(0, 0, 320, __MainScreen_Height)];
        if (IS_IOS_7)
        {
            recordView.frame = CGRectMake(0, 20, 320, __MainScreen_Height);
        }
        _recordView = recordView;
        NSString *fileName = @"myinfoSound.amr";
        NSString * audioPath = [AppComManager pathForMsgMedia:fileName];
        //如果存在文件，说明是重录，删除之前文件
        if ([FileManager fileExistsAtPath:audioPath])
        {
            [FileManager removeItemAtPath:audioPath error:nil];
        }
        _recordView.audioPath = audioPath;
        recordView.delegate = self;
        [self.navigationController.view addSubview:recordView];
        [recordView release];
    }
}

#pragma mark - 录音结束
/**
 * @函数名称：recordView:recordDidCompleted:recordTime:
 * @函数描述：录音结束，获取录音数据和录音时间长度
 * @输入参数：void
 * @输出参数：void
 * @返回值：void
 * @author：yinlinlin
 */
- (void)recordView:(RecordView *)recordView recordDidCompleted:(NSData *)audioData recordTime:(int)duration
{
    if([audioData length] < 100)
    {
        return;
    }
    NSMutableDictionary *sendDic = [NSMutableDictionary dictionaryWithCapacity:1];
    [sendDic setValue:@"amr" forKey:@"extname"];
    [AppComManager uploadBanBuBroadcastMedia:audioData mediaName:@"yuyin" par:sendDic delegate:self];
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"uploading", nil) activityAnimated:YES];
    [[AVAudioSession sharedInstance] setActive:NO error: nil];
    NSString *fileName = @"myinfoSound.amr";
    NSString * audioPath = [AppComManager pathForMsgMedia:fileName];
    //上传之前删除之前的录音文件
    if ([FileManager fileExistsAtPath:audioPath])
    {
        [FileManager removeItemAtPath:audioPath error:nil];
    }

}


- (void)banbuUploadRequest:(NSDictionary *)resDic didFinishedWithError:(NSError *)error
{
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0.0];
    
    if(error)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"uploadFailNotice", nil) activityAnimated:NO duration:2.0];
        return;
    }
    //    //NSLog(@"%@",resDic);
    if([[resDic valueForKey:@"ok"] boolValue])
    {
        [self setVoiceIntroduce:[resDic valueForKey:@"fileurl"]];
    }
    
}

-(void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    if(error)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"uploadFailNotice", nil) activityAnimated:NO duration:2.0];
        return;
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_Spaceset_Byuser])
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"modifySucceed", nil) activityAnimated:NO duration:1];
        [self.navigationController popViewControllerAnimated:YES];
        for(BanBu_PersonDataViewController *v in self.navigationController.viewControllers)
        {
            if([v isKindOfClass:[BanBu_PersonDataViewController class]])
            {
                [v getMyInfo];
            }
        }
    }
    else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Space_Picture_Sound_List])
    {
        [self.soundList addObjectsFromArray:[resDic valueForKey:@"list"]];
        [self.tableview reloadData];
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    _player.delegate = nil;
    [_player stop];
}


- (void)viewDidUnload {
    [self setHeaderView:nil];
    [self setVoiceView:nil];
    [self setBg:nil];
    [super viewDidUnload];
}
@end
